﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;


namespace Nivdal
{
    public partial class ListOfTeamMatches : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx");
            if (Request.QueryString["ConfirmNote"] != null)
            {
                this.ConfirmPanel.Visible = true;
                this.ConfirmNote.Text = Request.QueryString["ConfirmNote"].ToString();
            }
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            bool IsNationalTeam = false;

            string TeamId = null;
            if (Request.QueryString["TeamId"] != null)
                TeamId = Request.QueryString["TeamId"].ToString();
            else
                if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    Response.Redirect("~/Default.aspx");
                else
                {
                    if ((Request.QueryString["NationalTeam"] != null) && (ou.NationalTeamCoach != "0"))
                        TeamId = ou.NationalTeamCoach;
                    else
                        TeamId = ou.TeamId;
                }
            if (Request.QueryString["NationalTeam"] != null)
            {
                IsNationalTeam = true;
            }
            
            if (IsNationalTeam)
                IsNationalTeamHiddenField.Value = "true";
            else
                IsNationalTeamHiddenField.Value = "false";

            this.FutureMatchesLinkButton.NavigateUrl = "TeamFutureMatches.aspx?TeamId=" + TeamId + (IsNationalTeam ? "&NationalTeam=yes" : "");
            this.PastMatchesLinkButton.NavigateUrl = "TeamPastMatches.aspx?TeamId=" + TeamId + (IsNationalTeam ? "&NationalTeam=yes" : "");
            this.TeamHomePageLinkButton.NavigateUrl = (IsNationalTeam ? "NationalTeam.aspx?Id=" : "TeamHomePage.aspx?TeamId=") + TeamId;

            if (!IsPostBack)
            {
                this.CompletedMatchesSqlDataSource.SelectParameters.Add("TeamId", TeamId);
                ///this.CompletedMatchesSqlDataSource.SelectParameters.Add("Language", GND.GetUserLanguage());
                this.CompletedMatchesSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.CompletedMatchesSqlDataSource.SelectParameters.Add("IsNT", IsNationalTeam ? "1" : "0");
                this.OngoingMatchForTeamSqlDataSource.SelectParameters.Add("TeamId", TeamId);
                this.OngoingMatchForTeamSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.OngoingMatchForTeamSqlDataSource.SelectParameters.Add("IsNT", IsNationalTeam ? "1" : "0");
                this.UpcomingMatchesSqlDataSource.SelectParameters.Add("TeamId", TeamId);

                this.UpcomingMatchesSqlDataSource.SelectParameters.Add("Language", ou.Language);
                this.UpcomingMatchesSqlDataSource.SelectParameters.Add("IsNT", IsNationalTeam ? "1" : "0");
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                  this.UpcomingMatchesSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
                this.ShowStadiumsValuesSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
                this.ShowStadiumsValuesSqlDataSource.SelectParameters.Add("IsNT", IsNationalTeam ? "1" : "0");
                this.StadiumsCostSQLDataSourse.SelectParameters.Add("UserId", ou.UserId);
                this.StadiumsCostSQLDataSourse.SelectParameters.Add("IsNT", IsNationalTeam ? "1" : "0");
            }
            //this.ConfirmNote.Text = AreThereOngoingMatchesForTeam(UserTeamId()).ToString();
            //this.OngoingMatchesLabel.Visible = AreThereOngoingMatchesForTeam(UserTeamId());
            //this.OngoingMatchForTeamGridView.Visible = AreThereOngoingMatchesForTeam(UserTeamId());
            //if (this.OngoingMatchForTeamGridView.Rows.Count != null)
            //this.ConfirmPanel.Visible = true;
            //this.ConfirmNote.Text = this.OngoingMatchForTeamGridView.Rows.Count.ToString() + " koko";
            this.OngoingMatchesPanel.Visible = (this.OngoingMatchForTeamGridView.Rows.Count > 0);
            //this.OngoingMatchesPanel.Visible = false;
            string TeamName = GND.ReadNivdalStringData("TeamId", "IsNational", "Nivdal_GetTeamNameByTeamId", TeamId, IsNationalTeam ? "1" : "0");
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.ListOfTeamMatches_PageTitle + ": " + TeamName;
            //this.Title = TeamName + " " + " - Nivdal.com!";
            this.PageNameLabel.Text = TeamName + " " + Resources.Resource.ListOfTeamMatches_PageNameLabel;
        }

        protected void UpcomingMatchesGridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {   

            if ((e.Row.RowType == DataControlRowType.DataRow) || (e.Row.RowType == DataControlRowType.Header))
            {
                e.Row.Cells[0].Visible = false;
            }
        }

        protected bool IsStadiumAsignment(Object StadiumAsignment)
        {
            if (StadiumAsignment.ToString() == "True")
                return true;
            else
                return false;
        }

        protected void CompletedMatchesGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "BookmarkMatch")
            {
                //// get the row index stored in the CommandArgument property
                //int index = Convert.ToInt32(e.CommandArgument);
                //// get the GridViewRow where the command is raised
                //GridViewRow row = UpcomingMatchesGridView.Rows[index];
                //string MatchId = row.Cells[0].Text;
                //GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                //string UsrId = GND.ReturnUserId();
                //BookMarkTheMatch(UsrId, MatchId);
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                string Answer = GND.ReadNivdalStringData("BookmarkedMatch", "UserId", "Nivdal_BookmarkMatchSelect", e.CommandArgument, ou.UserId);
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + Answer);

            }
        }


        protected void OngoingMatchForTeamGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];            
            if (e.CommandName == "BookmarkMatch")
            {
                // get the row index stored in the CommandArgument property                
                string Answer = GND.ReadNivdalStringData("BookmarkedMatch", "UserId", "Nivdal_BookmarkMatchSelect", e.CommandArgument, ou.UserId);
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + Answer);
            }
            else if (e.CommandName == "AddToLive")
            {
                GND.ExecNivdalSQL("UserId", "MatchId", "Nivdal_LiveAddMatchToLive", ou.UserId, e.CommandArgument);
                Response.Redirect("Live.aspx");
            }
        }

        protected void UpcomingMatchesGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            // If multiple buttons are used in a GridView control, use the
            // CommandName property to determine which button was clicked.
            if (e.CommandName == "AssignStadium")
            {
                // get the row index stored in the CommandArgument property
                int index = Convert.ToInt32(e.CommandArgument);
                // get the GridViewRow where the command is raised
                GridViewRow row = UpcomingMatchesGridView.Rows[index];
                string MatchId = row.Cells[0].Text;
                DropDownList StadiumsDropDownList = (DropDownList)row.FindControl("StadiumsDropDownList");
                string StadiumId = StadiumsDropDownList.SelectedItem.Value;
                //Response.Write(StadiumsDropDownList.SelectedItem.Value);
                if (StadiumId.ToString() == "0")
                {
                    Response.Redirect("ListOfTeamMatches.aspx?ConfirmNote=" + Resources.Resource.ListOfTeamMatches_RedirectConfirmNote);
                }
                else
                    AssignTheStadium(MatchId, StadiumId);
            }

            else if (e.CommandName == "BookmarkMatch")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                string Answer = GND.ReadNivdalStringData("BookmarkedMatch", "UserId", "Nivdal_BookmarkMatchSelect", e.CommandArgument, ou.UserId);
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + Answer);
            }

            else if (e.CommandName == "AddToLive")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                GND.ExecNivdalSQL("UserId", "MatchId", "Nivdal_LiveAddMatchToLive", ou.UserId, e.CommandArgument);
                Response.Redirect("Live.aspx");
            }

        }

        protected bool IsAllowBookMark()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ou.IsPremium;
        }




        protected void AssignTheStadium(string MatchId, string StadiumId)
        {
            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_StadiumAssignStadiumToMatch";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_MatchId = new SqlParameter();
            dbParam_MatchId.ParameterName = "@MatchId";
            dbParam_MatchId.Value = MatchId;
            dbParam_MatchId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_MatchId);

            SqlParameter dbParam_StadiumId = new SqlParameter();
            dbParam_StadiumId.ParameterName = "@StadiumId";
            dbParam_StadiumId.Value = StadiumId;
            dbParam_StadiumId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_StadiumId);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                string NT = (IsNationalTeamHiddenField.Value == "true") ? "&NationalTeam=yes" : "";
                Response.Redirect("ListOfTeamMatches.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString() + NT);
            }
            catch (Exception SQLDBException)
            {
                this.ConfirmNote.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }
        }

        protected void BookMarkTheMatch(string UserId, string MatchId)
        {

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkMatch";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedMatch = new SqlParameter();
            dbParam_BookmarkedMatch.ParameterName = "@BookmarkedMatch";
            dbParam_BookmarkedMatch.Value = MatchId;
            dbParam_BookmarkedMatch.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedMatch);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.ConfirmNote.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }

        }

        //protected string GetIconByMatchType(object o)
        //{
            
        //    string ReturnValue = "~/Images/Icons/";
        //    //string Type = (string)o;
        //    int Type;
        //    try
        //    {
        //        Type = Int32.Parse(o.ToString());
        //    }
        //    catch
        //    {
        //        Type = 0;
        //    }


        //    switch (Type)
        //    {
        //        case 1:
        //            ReturnValue += "LeagueIcon.png";
        //            break;
        //        case 2:
        //            ReturnValue += "NationalCupIcon.png";
        //            break;
        //        case 3:
        //            ReturnValue += "InternationalCupIcon.png";
        //            break;
        //        default:
        //            ReturnValue += "FriendlyIcon.png";
        //            break;
        //    }
        //    return (ReturnValue);
        //}

        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }

        protected override void InitializeCulture()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {

                OnlineUser ou = (OnlineUser)Session["User"];
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
            }
        }

    }
}